package com.lmz.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lmz.common.TO.mq.OrderTo;
import com.lmz.common.TO.mq.SeckillOrderTo;
import com.lmz.common.TO.skuHasStockVo;
import com.lmz.common.utils.PageUtils;
import com.lmz.common.utils.Query;
import com.lmz.common.utils.R;
import com.lmz.common.vo.MemberResponseVo;
import com.lmz.order.constant.orderConstant;
import com.lmz.order.dao.OrderDao;
import com.lmz.order.entity.OrderEntity;
import com.lmz.order.entity.OrderItemEntity;
import com.lmz.order.entity.PaymentInfoEntity;
import com.lmz.order.enume.OrderStatusEnum;
import com.lmz.order.feign.CartFeignService;
import com.lmz.order.feign.MemberFeignService;
import com.lmz.order.feign.ProductFeignService;
import com.lmz.order.feign.WmsFeignService;
import com.lmz.order.interceptor.LoginUserInterceptor;
import com.lmz.order.service.OrderItemService;
import com.lmz.order.service.OrderService;
import com.lmz.order.service.PaymentInfoService;
import com.lmz.order.to.orderCreatTo;
import com.lmz.order.vo.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    private ThreadLocal<OrderSubmitVo> ThreadLocal = new ThreadLocal<>();
    @Autowired
    private MemberFeignService memberFeignService;
    @Autowired
    private CartFeignService cartFeignService;
    @Autowired
    private WmsFeignService wmsFeignService;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ThreadPoolExecutor executor;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private PaymentInfoService paymentInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<>()
        );
        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
        //获取之前的请求上下文，每一个线程都要能获取到之前的上下文信息
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> getAddress = CompletableFuture.runAsync(() -> {
            //远程查询收获地址列表
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> address = memberFeignService.getAddress(memberResponseVo.getId());
            confirmVo.setAddress(address);
        }, executor);
        CompletableFuture<Void> getCartItems = CompletableFuture.runAsync(() -> {
            //查询购物车选中的购物项
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> CartItems = cartFeignService.getCurrentUserCartItems();
            confirmVo.setItems(CartItems);
        }, executor).thenRunAsync(() -> {
            //查询是否有库存
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            List<skuHasStockVo> data = wmsFeignService.getSkusStock(collect);
            if (data != null) {
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(skuHasStockVo::getSkuId, skuHasStockVo::getHasStock));
                confirmVo.setStocks(map);
            }
        }, executor);
        //查询积分信息
        Integer integration = memberResponseVo.getIntegration();
        confirmVo.setIntegration(integration);
        //其他数据在实体类中进行了自动计算
        //防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        confirmVo.setOrderToken(token);
        redisTemplate.opsForValue().set(orderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId(), token, 30, TimeUnit.MINUTES);

        CompletableFuture.allOf(getAddress, getCartItems).get();
        //计算应付价格
        confirmVo.setPayPrice(confirmVo.getTotal());

        return confirmVo;
    }

    //@GlobalTransactional   seata
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        SubmitOrderResponseVo response = new SubmitOrderResponseVo();
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
        ThreadLocal.set(vo);
        response.setCode(0);
        //验证令牌[令牌的验证和删除必须保证原子性---使用LUA脚本]
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();
        //验证和删除令牌--保证了原子性
        Long result = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class),
                Arrays.asList(orderConstant.USER_ORDER_TOKEN_PREFIX + memberResponseVo.getId()), orderToken);
        if (result == 0L) {
            //验证失败
            response.setCode(1);
            return response;
        } else {
            //下单一系列操作
            //创建订单,订单项等信息
            orderCreatTo order = creatOrder();
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            if (Math.abs(payPrice.subtract(payAmount).doubleValue()) < 0.01) {
                //价格对比成功
                //保存订单
                saveOrder(order);
                //订单号，订单项信息（skuId，num，skuName）
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());

                List<OrderItemVo> locks = order.getOrderItems().stream().map(item -> {
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setCount(item.getSkuQuantity());
                    itemVo.setTitle(item.getSkuName());
                    return itemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(locks);
                //库存锁定,有异常回滚订单数据
                R r = wmsFeignService.orderLockStock(lockVo);
                if (r.getCode() == 0) {
                    response.setOrder(order.getOrder());
                    //订单创建成功，发送消息给mq
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
                    return response;
                } else {
                    throw new RuntimeException();
                }
            } else {
                //价格对比失败
                response.setCode(2);
                return response;
            }
        }
    }

    @Override
    public OrderTo getOrderByOrderSn(String orderSn) {
        OrderEntity orderEntity = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        OrderTo orderTo = new OrderTo();
        BeanUtils.copyProperties(orderEntity, orderTo);
        return orderTo;
    }


    /**
     * 保存订单数据
     */
    private void saveOrder(orderCreatTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);
        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }

    private orderCreatTo creatOrder() {
        orderCreatTo orderCreatTo = new orderCreatTo();
        //生成订单号--mybatis-plus提供
        String orderSn = IdWorker.getTimeId();
        //创建订单
        OrderEntity order = buildOrder(orderSn);
        //获取所有的订单项
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);
        orderCreatTo.setOrder(order);
        orderCreatTo.setOrderItems(itemEntities);
        //对比价格
        computePrice(order, itemEntities);

        return orderCreatTo;
    }

    /**
     * 订单价格相关
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal gift = new BigDecimal("0");
        BigDecimal growth = new BigDecimal("0");
        for (OrderItemEntity entity : itemEntities) {
            BigDecimal realAmount = entity.getRealAmount();
            total = total.add(realAmount);
            //积分和成长值
            gift = gift.add(new BigDecimal(entity.getGiftIntegration().toString()));
            growth = growth.add(new BigDecimal(entity.getGiftGrowth().toString()));
        }
        //总价
        orderEntity.setTotalAmount(total);
        //应付:总价+运费
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(new BigDecimal("0"));
        orderEntity.setIntegrationAmount(new BigDecimal("0"));
        orderEntity.setCouponAmount(new BigDecimal("0"));
        //积分信息
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(growth.intValue());
    }

    /**
     * 创建一个订单
     */
    private OrderEntity buildOrder(String orderSn) {
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        //会员id
        orderEntity.setMemberId(memberResponseVo.getId());
        //计算运费信息
        OrderSubmitVo orderSubmitVo = ThreadLocal.get();
        orderEntity.setFreightAmount(new BigDecimal("0"));
        //设置地址信息
        R r = memberFeignService.addrInfo(orderSubmitVo.getAddrId());
        MemberAddressVo address = r.getData("memberReceiveAddress", new TypeReference<MemberAddressVo>() {
        });
        orderEntity.setReceiverCity(address.getCity());
        orderEntity.setReceiverDetailAddress(address.getDetailAddress());
        orderEntity.setReceiverName(address.getName());
        orderEntity.setReceiverPhone(address.getPhone());
        orderEntity.setReceiverPostCode(address.getPostCode());
        orderEntity.setReceiverProvince(address.getProvince());
        orderEntity.setReceiverRegion(address.getRegion());
        //设置订单状态
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        //默认自动确认的时间
        orderEntity.setAutoConfirmDay(7);
        orderEntity.setDeleteStatus(0); //代表未删除
        return orderEntity;
    }

    /**
     * 构建所有订单项数据
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        if (currentUserCartItems != null && currentUserCartItems.size() > 0) {
            List<OrderItemEntity> itemEntities = currentUserCartItems.stream().map(cartItem -> {
                OrderItemEntity itemEntity = buildOrderItem(cartItem);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;
    }

    /**
     * 构建一个订单项
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        //商品的spu
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo data = r.getData("data", new TypeReference<SpuInfoVo>() {
        });
        itemEntity.setSpuId(data.getId());
        itemEntity.setSpuBrand(data.getBrandId().toString());
        itemEntity.setSpuName(data.getSpuName());
        itemEntity.setCategoryId(data.getCatalogId());
        //商品的sku
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());
        //优惠信息---此处忽略
        //积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().intValue());

        //订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        itemEntity.setCouponAmount(new BigDecimal("0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0"));
        //实际金额--总价*数量减去优惠金额
        BigDecimal original = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        itemEntity.setRealAmount(original);

        return itemEntity;
    }

    /**
     * 关闭订单逻辑
     */
    @Override
    public void closeOrder(OrderEntity order) {
        //查询订单的最新状态
        OrderEntity orderEntity = this.getOne(new QueryWrapper<OrderEntity>().
                eq("order_sn", order.getOrderSn()));
        if (orderEntity.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())) {
            //关闭订单
            OrderEntity update = new OrderEntity();
            update.setId(orderEntity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);

            //订单解锁成功再给mq发送消息释放库存（有可能订单任务慢于库存业务，导致库存不能进行解锁）
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity, orderTo);
            try {
                //需要保证消息一定可以发送出去，可以做日志记录---存入数据库
                //定期扫描数据库将失败的消息重新发送
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
            } catch (Exception e) {
                //TODO 将未发送成功的消息重复发送
            }
        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderTo order = this.getOrderByOrderSn(orderSn);
        List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity itemEntity = order_sn.get(0);
        BigDecimal amount = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(amount.toString());
        payVo.setOut_trade_no(order.getOrderSn());
        payVo.setSubject(itemEntity.getSkuName());
        payVo.setBody(itemEntity.getSkuAttrsVals());
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
        QueryWrapper<OrderEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("member_id", memberResponseVo.getId());
        wrapper.orderByDesc("id");
        IPage<OrderEntity> page = this.page(new Query<OrderEntity>().getPage(params), wrapper);
        List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> orderItems = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(orderItems);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(order_sn);
        return new PageUtils(page);
    }

    /**
     * 处理支付宝的支付结果
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        //1.保存交易流水
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setPaymentStatus(vo.getTrade_status());
        infoEntity.setCallbackTime(vo.getNotify_time());
        paymentInfoService.save(infoEntity);
        //修改订单状态信息
        String trade_status = vo.getTrade_status();
        if (trade_status.equals("TRADE_SUCCESS") || trade_status.equals("TRADE_FINISHED")) {
            String outTradeNo = vo.getOut_trade_no();
            this.updateOrderStatus(outTradeNo, OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }


    private void updateOrderStatus(String outTradeNo, Integer code) {
        this.baseMapper.updateOrderStatus(outTradeNo, code);
    }

    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrderTo) {
        //保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrderTo.getOrderSn());
        orderEntity.setMemberId(seckillOrderTo.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal totalPay = seckillOrderTo.getSeckillPrice().multiply(new BigDecimal("" + seckillOrderTo.getNum()));
        orderEntity.setPayAmount(totalPay);
        this.save(orderEntity);

        //保存订单项信息
        OrderItemEntity itemEntity = new OrderItemEntity();
        itemEntity.setOrderSn(seckillOrderTo.getOrderSn());
        itemEntity.setRealAmount(totalPay);
        itemEntity.setSkuQuantity(seckillOrderTo.getNum());

        orderItemService.save(itemEntity);

    }

}